﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WikiDoc.Utils
{
    /// <summary>
    /// 一个简单的输出缓冲区，每次输出一行，自动在各行之间添加换行符。
    /// </summary>
    public class OutputBuffer
    {
        private readonly StringBuilder _buffer = new StringBuilder();

        /// <summary>
        /// 追加一行，换行符并不会立即追加到最后，而是要等到下一次追加时才会追加。
        /// </summary>
        /// <param name="line">The line.</param>
        /// <returns></returns>
        public OutputBuffer AppendLine(string line)
        {
            if (_buffer.Length > 0 && !IsAtLineStart()) _buffer.AppendLine();

            _buffer.Append(line);

            return this;
        }

        /// <summary>
        /// 当前是否在一行的开头位置
        /// </summary>
        public bool IsAtLineStart()
        {
            var ch = _buffer.Length == 0 ? '\0' : _buffer[_buffer.Length - 1];

            return ch == '\r' || ch == '\n' || ch == '\0';
        }

        /// <summary>
        /// 缓冲区当前包含的行数
        /// </summary>
        public int Length
        {
            get { return _buffer.Length; }
        }

        /// <summary>
        /// 清除缓冲区
        /// </summary>
        public void Clear()
        {
            _buffer.Length = 0;
        }

        /// <summary>
        /// 获取当前缓冲区内所有内容并清空缓冲区
        /// </summary>
        /// <returns></returns>
        public string Flush()
        {
            var ret = ToString();
            Clear();
            return ret;
        }

        /// <summary>
        /// 获取缓冲区当前文本
        /// </summary>
        /// <returns>
        /// A <see cref="System.String"/> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return _buffer.ToString();
        }
    }
}
